package Server.Cache;

import Protobuf.ChatProto;
import Server.Common.Player;
import Server.Common.World;
import Server.ServerHandler;
import io.netty.channel.Channel;

public class MsgSession {

    private final String id;

    private final Channel channel;

    private ChatProto.Msg msg;

    private ChannelState channelState;

    public MsgSession(Channel channel,ChannelState channelState){
        this.channel = channel;
        this.id = channel.id().asLongText();
        this.channelState = channelState;
    }

    public void sendPacket(){
        if (msg == null) {
            return;
        }
        channel.writeAndFlush(msg);
    }

    public void setMsg(ChatProto.Msg msg){
        this.msg = msg;
    }

    public ChatProto.Msg getMsg(){
        return msg;
    }

    public String getChannelId(){
        return id;
    }

    public Channel getChannel(){
        return this.channel;
    }

    public void saveChannel(){
        ChannelCache.getInstance().putChannel(id,channel);
    }

    public void disconnected(){
        PlayerCache cache = PlayerCache.getInstance();
        Player player =cache.getPlayer(channel);
        ChannelCache.getInstance().removeChannel(id);
        ServerHandler.scene.removeMember(player);
        World.getInstance().removeLoginOutPlayer(player);
        System.out.println(player.getId()+" 下线了\n");
    }

    public ChannelState getChannelState() {
        return channelState;
    }

    public void setChannelState(ChannelState channelState) {
        this.channelState = channelState;
    }
}
